package cc.linker.steplink.crm.merchant.controller.integral;

import cc.linker.steplink.crm.commons.model.FormLoginDto;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.utils.CharUtils;
import cc.linker.steplink.crm.merchant.service.acs.MerchantInfoService;
import cc.linker.steplink.crm.merchanth5.commons.FormFilter;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.merchant.service.integral.IntegralGoodsService;
import cc.linker.steplink.crm.response.GlobalException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/integral/goods")
public class IntegralGoodsController {

    @Autowired
    private IntegralGoodsService integralGoodsService;
    @Autowired
    private UserInfoUtil userInfoUtil;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private FormFilter formFilter;

    /**
     * 积分商城规则
     *
     */
    @GetMapping("/getrule")
    public Object getrule(HttpServletRequest request, Integer ruleType){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        if(ruleType==null){
            ruleType =1;
        }
        return integralGoodsService.getrule(orgId,ruleType);
    }
    /**
     * 保存积分商城规则
     * @param ：rule 规则
     *
     */
    @PostMapping("/saverule")
    public void saverule(@RequestBody Map<String, Object> param,HttpServletRequest request){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        param.put("orgId",orgId);
        integralGoodsService.saverule(param);
    }


    /**
     * 商品列表
     *
     * @param ：pageIndex 页码
     * @param ： pageSize  页面大小
     * @param ： goodsStatus    状态
     * @param ： key       关键字
     */
    @GetMapping("/list")
    public Object getGoodsList(@RequestParam(value = "status", defaultValue = "0", required = false) Integer status,
                               @RequestParam(value = "key", defaultValue = "", required = false) String key,
                               @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
                               @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                               @RequestParam(value = "goodsType", defaultValue = "-1", required = false) Integer goodsType,
                               Long groupId,HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String, Object> params = new HashMap<>();
        String orgId = userinfo.getOrgId();
        params.put("orgId", orgId);
        if (!StringUtils.isEmpty(key)) {
            try {
                key = URLDecoder.decode(key.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
                key = key.replaceAll("%", "/%");
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        params.put("key", key);
        params.put("goodsStatus", status);
        params.put("pageIndex", pageIndex);
        params.put("pageSize", pageSize);
        params.put("goodsType", goodsType);
        params.put("groupId", groupId);
        return integralGoodsService.getGoodsList(params);
    }

    /**
     * 积分商品排序
     *
     * @param ： goodsId 商品 id
     * @param ： sort 当前商品排序
     * @param ： type 0 向下 1 向上
     *
     */
    @PostMapping("/updateSort")
    public void updateSort(@RequestBody Map<String, Object> param, HttpServletRequest request)
    {
        if(StringUtils.isEmpty(param.get("goodsId")) || StringUtils.isEmpty(param.get("sort")) || StringUtils.isEmpty(param.get("type"))){
            throw GlobalException.build("参数不能为空！");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Long goodsId = Long.valueOf(param.get("goodsId").toString());
        Integer sort = Integer.valueOf(param.get("sort").toString());
        Integer type = Integer.valueOf(param.get("type").toString());
        String orgId = userinfo.getOrgId();
        integralGoodsService.updateSort(goodsId,sort,type,orgId);
    }

    /**
     * 积分商品删除
     *
     * @param ： goodsId 商品 id
     *
     */
    @PostMapping("/delete")
    public void delete(@RequestBody Map<String, Object> param, HttpServletRequest request){
        if(StringUtils.isEmpty(param.get("goodsId"))){
            throw GlobalException.build("参数不能为空！");
        }
        Long goodsId = Long.valueOf(param.get("goodsId").toString());
        integralGoodsService.delete(goodsId);
    }

    /**
     * 积分商品上下架
     *
     * @param ： goodsId         商品 id
     * @param ： goodsStatus 	商品状态 1上架 0下架
     *
     */
    @PostMapping("/updateStatus")
    public void updateStatus(@RequestBody Map<String, Object> param, HttpServletRequest request){
        if(StringUtils.isEmpty(param.get("goodsId")) || StringUtils.isEmpty(param.get("goodsStatus"))){
            throw GlobalException.build("参数不能为空！");
        }
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        integralGoodsService.updateStatus(param, userinfo.getSaler());
    }

    /**
     * 商品新增编辑
     *
     * @param ：goodsBanner      商品图片(数组)
     * @param ：goodsContent     商品简介
     * @param ：goodsCount       商品数量
     * @param ：goodsCover       商品封面
     * @param ：goodsId          商品id,编辑时传
     * @param ：goodsName        商品名
     * @param ：goodsSpec        规格
     * @param ：goodsStatus      商品状态
     * @param ：integral         兑换积分数
     * @param ：originalPrice    原价
     * @param ：sku              规格值
     * @param ：videoContent     视频内容
     * @param ：videoCover       视频封面
     * @param ：videoResId       视频资源id
     * @param ：shareTitle       分享标题
     * @param ：shareInfo        分享简介
     * @param ：quotaNum         限购件数
     * @param ：quotaLevel       限购会员等级
     *
     */
    @PostMapping("/save")
    public void save(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String adminId = userinfo.getAdminId();
        params.put("orgId", orgId);
        params.put("adminId", adminId);
        integralGoodsService.save(params,orgId);
    }


    /**
     * 商品详情
     *
     * @param ： goodsId  商品id
     */
    @GetMapping("/getGoodsInfo")
    public Object getGoodsInfo(Long goodsId) {
        return integralGoodsService.getGoodsInfo(goodsId);
    }

    /**
     * 兑换列表
     *
     */
    @GetMapping("/exchangelist")
    public Object exchangelist(@RequestParam(value = "user", defaultValue = "", required = false) String user,
                               @RequestParam(value = "phone", defaultValue = "", required = false) String phone,
                               @RequestParam(value = "goodsName", defaultValue = "", required = false) String goodsName,
                               @RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
                               @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                               String startTime, String endTime,HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> params = new HashMap<>();
        if (userinfo.getSaler()) {
            //小b查看只展示自己的商品
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            params.put("customerId", customerId);
        }else {
            params.put("customerId", "");
        }
        try {
            if (!StringUtils.isEmpty(goodsName)) {
                goodsName = URLDecoder.decode(goodsName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
                goodsName = goodsName.replaceAll("%", "/%");
            }

            if (!StringUtils.isEmpty(user)) {
                user = URLDecoder.decode(user.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
                user = user.replaceAll("%", "/%");
            }
            if (!StringUtils.isEmpty(phone)) {
                phone = URLDecoder.decode(phone.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
                phone = phone.replaceAll("%", "/%");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        if (!StringUtils.isEmpty(startTime)) {
            startTime += " 00:00:00";
        }
        if (!StringUtils.isEmpty(endTime)) {
            endTime += " 23:59:59";
        }

        params.put("goodsName", goodsName);
        params.put("phone", phone);
        params.put("user", user);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("orgId", orgId);
        params.put("belongId", orgId);
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(integralGoodsService.exchangelist(params));
    }

    /**
     * 导出兑换列表
     *
     */
    @GetMapping("/exportExchangelist")
    public void exportExchangelist(@RequestParam(value = "user", defaultValue = "", required = false) String user,
                               @RequestParam(value = "phone", defaultValue = "", required = false) String phone,
                               @RequestParam(value = "goodsName", defaultValue = "", required = false) String goodsName,
                               String startTime, String endTime,HttpServletRequest request, HttpServletResponse response) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String, Object> params = new HashMap<>();
        if (userinfo.getSaler()) {
            //小b查看只展示自己的商品
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            params.put("customerId", customerId);
        }else {
            params.put("customerId", "");
        }
        try {
            if (!StringUtils.isEmpty(goodsName)) {
                goodsName = URLDecoder.decode(goodsName.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
                goodsName = goodsName.replaceAll("%", "/%");
            }

            if (!StringUtils.isEmpty(user)) {
                user = URLDecoder.decode(user.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
                user = user.replaceAll("%", "/%");
            }
            if (!StringUtils.isEmpty(phone)) {
                phone = URLDecoder.decode(phone.replaceAll("%(?![0-9a-fA-F]{2})", "%25"), "UTF-8");
                phone = phone.replaceAll("%", "/%");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        if (!StringUtils.isEmpty(startTime)) {
            startTime += " 00:00:00";
        }
        if (!StringUtils.isEmpty(endTime)) {
            endTime += " 23:59:59";
        }
        params.put("goodsName", goodsName);
        params.put("phone", phone);
        params.put("user", user);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        params.put("orgId", orgId);
        params.put("belongId", orgId);
        integralGoodsService.exportExchangelist(params,response);
    }


    /**
     * 联盟共享库积分商品列表
     *
     * @param pageIndex 页码
     * @param pageSize  页面大小
     */
    @GetMapping("/allianceShareList")
    public PageInfo allianceShareList(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
                                      @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                      @RequestParam(value = "goodsName", defaultValue = "") String goodsName,
                                      @RequestParam(value = "phone", defaultValue = "") String phone,
                                      @RequestParam(value = "merchant", defaultValue = "") String merchant,
                                      @RequestParam(value = "orgMall", defaultValue = "-1") Integer orgMall,
                                      HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        Map<String,Object> params = new HashMap<>();
        params.put("pageIndex", pageIndex);
        params.put("pageSize", pageSize);
        if(!StringUtils.isEmpty(goodsName)){
            params.put("goodsName", CharUtils.escapeQueryChars(goodsName));
        }
        if(!StringUtils.isEmpty(merchant)){
            params.put("merchant", CharUtils.escapeQueryChars(merchant));
        }
        params.put("phone",phone);
        params.put("orgMall",orgMall);
        params.put("orgId", userinfo.getOrgId());
        params.put("ifSales", userinfo.getSaler());
        params.put("adminId", userinfo.getAdminId());
        return integralGoodsService.allianceShareList(params);
    }

    /**
     * 我的共享-积分商品
     * @param pageIndex
     * @param pageSize
     * @param request
     * @return
     */
    @GetMapping("/getmysharegoodslist")
    public PageInfo getMyShareGoodsList(@RequestParam(value = "pageIndex", defaultValue = "1", required = false) Integer pageIndex,
                                        @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
                                        @RequestParam(value = "goodsName", defaultValue = "") String goodsName,
                                        HttpServletRequest request){
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        Map<String,Object> param = new HashMap<>();
        param.put("orgId",orgId);
        if(!StringUtils.isEmpty(goodsName)){
            param.put("goodsName", CharUtils.escapeQueryChars(goodsName));
        }
        if (userinfo.getSaler()) {
            //小b查看只展示自己的商品
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("belongId", customerId);
        }
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(integralGoodsService.getMyShareGoodsList(param));
    }

    /**
     * 共享、取消共享
     * @param request
     * @param param
     */
    @PostMapping("/savesharing")
    public Object saveSharing(HttpServletRequest request,@RequestBody Map<String, Object> param){
        FormLoginDto formLoginDto = formFilter.getFormLoginDto(request, false);
        param.put("formLoginDto",formLoginDto);
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String orgId = userinfo.getOrgId();
        String customerId = orgId;
        param.put("orgId",orgId);
        if (userinfo.getSaler()) {
            //小b查看活动只展示自己的活动
            customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            param.put("createUserId", customerId);
        }
        return integralGoodsService.saveSharing(param);
    }

    /**
     * 添加/移除至(从)商城
     *
     */
    @PostMapping("/addToMall")
    public void addToMall(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        if(userinfo.getSaler()){
            String customerId = merchantInfoService.getCustomerIdByAdminId(userinfo.getAdminId());
            params.put("customerId", customerId);
        }
        params.put("orgId", userinfo.getOrgId());
        integralGoodsService.addToMall(params);
    }
}
